﻿#region Librerias

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ESF.SSO.Presenter.Admin.User;
using ESF.Web.Pages;
using ESF.Web;
using ESF.General.Entity;
using ESF.General;
using ESF.SSO.Web.Tools.Modules;
using ESF.SSO.Core.Entities;
using ESF.SSO.Presenter.Admin;
using ESF.SSO.Core.Entities.BasicReferences;

#endregion


public partial class User_EditUser : BaseEditPage<EditUserPresenter, IEditUserViewer, User>, IEditUserViewer
{
	#region Carga Inicial

	protected void Page_Load(object sender, EventArgs e)
	{
		_Presenter = new EditUserPresenter (this);
	
		if (!IsPostBack)
		{
			ListLoader.LoadList (ddlUserIdentificationType, WebGeneral.ListBasicReference (BasicReferenceTypes.IdentificationType));
			ListLoader.LoadList (ddlUserGender, WebGeneral.ListBasicReference (BasicReferenceTypes.Gender));
			ListLoader.LoadList (ddlUserSecurityQuestion, WebGeneral.ListBasicReference (BasicReferenceTypes.SecurityQuestion));
			ListLoader.LoadList (chkUserGroups, WebGeneral.ListBasicReference (BasicReferenceTypes.UserGroup));


			btnGoBack.OnClientClick = JS.GenerateGoBack();
			
			
			// Editar sus datos de usuario corriente no puede editar nada mas
			if (string.IsNullOrEmpty (Request.QueryString ["ItemID"]) && string.IsNullOrEmpty (Request.QueryString ["new"]))
			{
				ItemID = AuthenticationModule.SignedInUser.ID;
				
				lbltitUserIsEnabled.Visible = false;
				divUserIsEnabled.Visible = false;
				btnGoBack.OnClientClick = JS.GenerateGoToFinal(ReadConfig.MainURL);
				
				tabAuditory.Visible = false;
				tabUserGroups.Visible = false;
				tabRights.Visible = false;
				tabExtraStep.Visible = false;

				lbltitUserPassword.Visible = false;
				btnAutoResetPassword.Visible = false;
				btnClear.Visible = false;

				btnSave.Enabled = AuthenticationModule.GetUserRightBool ("PuedeEditarSusDatosUsuario");

				if (!btnSave.Enabled)
				{	
					JS.AddWarning (this, "En este formulario solo puede visualizar sus datos y cambiar su contraseña");
				}

				txtUserAlias.Enabled = false;

				chkNotifyUserEmail.Visible = false;

				btnChangePassword.Visible = true;
			}

			_Presenter.Load();
		}
		
		btnAutoResetPassword.Enabled = (this.ItemID != null);
	}


	private void LoadIframes ()
	{
		if (!DataHelper.IsEmpty (ExtraAppSteps))
		{
			// TODO: soportar mas de una aplicacion
			foreach (BasicReference app in ExtraAppSteps)
			{
				ifrExtraStep.Attributes["src"] = RequestHelper.AppendVarValueToHTTPURL(app.Extra_I + "/" + app.Extra_II, "UserID", (ItemID == null ? string.Empty : ItemID.ToString ()), PageHelper.KEY_SETDOCUMENTDOMAIN, AuthenticationModule.TicketDomain);
			}

			tabExtraStep.Visible = true;

			JS.AddEndJS (Page, "ifrStep_3_IsValid = function (source, args) { var ifr = document.getElementById ('" + ifrExtraStep.ClientID + "'); args.IsValid = ifr.contentWindow.IsValid (); }");

			cvlIframeOtherApps.ClientValidationFunction = "ifrStep_3_IsValid";
		}
		else
		{
			tabExtraStep.Visible = false;
		}
	}
	
	#endregion
	
	
	#region Metodos de Autocompletado

	[System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
	public static string[] QueryCountriesByName (string prefixText, int count)
	{
		return DataHelper.ConvertToStringArray (GeneralAdmin.QueryBasicReferenceList(BasicReferenceTypes.Country, prefixText, count));
	}


	[System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
	public static string[] QueryCitiesByName(string prefixText, int count)
	{
		return DataHelper.ConvertToStringArray(GeneralAdmin.QueryBasicReferenceList(BasicReferenceTypes.City, prefixText, count));
	}
	
	#endregion


	#region Campos de ISignUpViewer

	public string UserNewPassword 
	{
		set { txtNewPassword.Text = value; }
		get { return txtNewPassword.Text; } 
	}


	public new int? ItemID 
	{
		get
		{
			return base.ItemID;
		}
		set 
		{
			base.ItemID = value; 
			
			if (!DataHelper.IsEmpty(ExtraAppSteps))
			{
				JS.AddEndJS (Page, "function CompleteSignUp () { var ifrx = document.getElementById ('" + ifrExtraStep.ClientID + "'); ifrx.contentWindow.SetUser ('" + value + "'); }; CompleteSignUp ();");
			}
		}
	}


	public List<BasicReference> UserRights
	{
		set { uscEditRights.Values = value; }
		get { return uscEditRights.Values; }
	}


	public List<BasicReference> ExtraAppSteps
	{
		get
		{
			return ViewState ["ExtraAppSteps"] as List<BasicReference>;
		}
		set 
		{
			ViewState ["ExtraAppSteps"] = value;

			LoadIframes ();
		}  
	}

	public bool IsEnabledResetPassword
	{
		set { btnAutoResetPassword.Enabled = value; }
	}


	public string UserAlias
	{
		set { txtUserAlias.Text = value; }
		get { return txtUserAlias.Text; }
	}

	public string UserFirstName
	{
		set { txtUserFirstName.Text = value; }
		get { return txtUserFirstName.Text; }
	}

	public string UserSecondName
	{
		set { txtUserSecondName.Text = value; }
		get { return txtUserSecondName.Text; }
	}

	public string UserSurName
	{
		set { txtUserSurName.Text = value; }
		get { return txtUserSurName.Text; }
	}

	public string UserLastName
	{
		set { txtUserLastName.Text = value; }
		get { return txtUserLastName.Text; }
	}

	public int? UserIdentificationTypeID
	{
		set 
		{
			ListLoader.Select (ddlUserIdentificationType, value);
		}
		get 
		{
			return TextHelper.GetNullableInt (ddlUserIdentificationType.SelectedValue); 
		}
	}

	public string UserIdentificationNumber
	{
		set { txtUserIdentificationNumber.Text = value; }
		get { return txtUserIdentificationNumber.Text; }
	}

	public string UserEmail
	{
		set { txtUserEmail.Text = value; }
		get { return txtUserEmail.Text; }
	}

	public Location Location
	{
		set { uscUserEditLocation.Location = value; }
		get { return uscUserEditLocation.Location; }
	}

	public int? UserSecurityQuestionID
	{
		set 
		{
			ListLoader.Select (ddlUserSecurityQuestion, value);
		}
		get { return TextHelper.GetNullableInt (ddlUserSecurityQuestion.SelectedValue); }
	}

	public string UserSecurityQuestionAnswer
	{
		set { txtUserSecurityQuestionAnswer.Text = value; }
		get { return txtUserSecurityQuestionAnswer.Text; }
	}

	public string UserEnterprise
	{
		set { txtUserEnterprise.Text = value; }
		get { return txtUserEnterprise.Text; }
	}

	public int? UserGenderID
	{
		set 
		{ 
			ListLoader.Select (ddlUserGender,value);
		}
		get { return TextHelper.GetNullableInt (ddlUserGender.SelectedValue); }
	}
	
	public DateTime? UserBirthDate
	{
		set 
		{
			if (value == null) { txtUserBirthDate.Text = string.Empty; }
			else { txtUserBirthDate.Text = value.Value.ToString (txtUserBirthDate_CalendarExtender.Format); } 
		}
		get { return TextHelper.GetNullableDate (txtUserBirthDate.Text); }
	}
	
	public bool? UserIsEnabled
	{
		set
		{
			if (value == null || !value.Value)
			{
				chkUserIsEnabled.Checked = false;
			}
			else
			{
				chkUserIsEnabled.Checked = true;
			}
		}
		get
		{
			return chkUserIsEnabled.Checked;
		}
	}
	
	
	public List<ESF.General.Entity.BasicReference> UserGroups
	{
		set
		{
			ListLoader.Select (chkUserGroups, value);
		}
		get
		{
			return ListLoader.GetSelectedItemsBasRef (chkUserGroups).ToList ();
		}
	}
	
	
	public bool NotifyUserEmail
	{
		set
		{
			chkNotifyUserEmail.Checked = value;
		}
		get
		{
			return chkNotifyUserEmail.Checked;
		}
	}


	public string UserProfession 
	{
		set { txtUserProfession.Text = value; }
		get { return txtUserProfession.Text; }
	}


	public string UserPosition
	{
		set { txtUserPosition.Text = value; }
		get { return txtUserPosition.Text; }
	}
	
	#endregion
	
	
	#region Auditoria
	
	public string UserCreationAlias
	{
		set
		{
			lblUserCreationAlias.Text = value;
		}
		get
		{
			return AuthenticationModule.SignedInUserAlias;
		}
	}
	
	
	public string UserLastUpdateAlias
	{
		set
		{
			lblUserLastUpdateAlias.Text = value;
		}
	}


	public DateTime? CreationDateTime
	{
		set
		{
			if (value != null)
			{
				lblCreationDateTime.Text = value.ToString();
			}
			else
			{
				lblCreationDateTime.Text = string.Empty;
			}
		}
	}
	
	
	public DateTime? LastUpdateDateTime
	{
		set
		{
			if (value != null)
			{
				lblLastUpdateDateTime.Text = value.ToString ();
			}
			else
			{
				lblLastUpdateDateTime.Text = string.Empty;
			}
		}
	}
	
	#endregion
	
	
	#region Eventos
	
	protected void btnAutoResetPassword_Click (object sender, EventArgs e)
	{
		_Presenter.AutoResetPassword ();
	}

	protected void btnChangePassword_Click(object sender, EventArgs e)
	{
		divChangePassword.Visible = true;
		txtNewPassword.Focus ();

		JS.AddEndJS (Page, string.Format ("ShowOverByID ('{0}');", divChangePassword.ClientID));
	}
	
	protected void btnSetNewPassword_Click(object sender, EventArgs e)
	{
		if (_Presenter.SetNewPassword ())
		{
			JS.AddEndJS (Page, string.Format ("HideOverByID ('{0}');", divChangePassword.ClientID));
		}
	}


	protected void btnCancelNewPassword_Click(object sender, EventArgs e)
	{
		txtNewPassword.Text = string.Empty;

		JS.AddEndJS (Page, string.Format ("HideOverByID ('{0}');", divChangePassword.ClientID));
	}

	#endregion
	
}
